/**
 * @author mikegill74
 * @scompid TSTDRV842652
 * @datemod 24/5/11
 */
var context = nlapiGetContext();

/**
 *
 *  Base64 encode / decode
 *  http://www.webtoolkit.info/
 *
 **/
function fnReadCSV(request, response){
    if (request.getMethod() == 'GET') {
        var form = nlapiCreateForm("Suitelet - Data Loader");
        
        form.addField('batch', 'text', 'Batch Name');
        form.addField('fileid', 'text', 'File Id');
        
        form.addSubmitButton('Submit');
        response.writePage(form);
    }
    else {
        var form = nlapiCreateForm("SuiteLet - Data Loader")
        
        var intFileId = request.getParameter('fileid');
        
        var fileObj = nlapiLoadFile(intFileId);
        var fileContents = fileObj.getValue();
        
        var fileArray = [];
        var contentsArray = [];
        
        fileArray = CSVToArray(fileContents, ',');
        
        for (var i = 1; i < fileArray.length; i++) {
            var contentsObject = new Object();
            var results = String(fileArray[i]).split(',', 15);
            
            contentsObject.position1 = results[0];
            contentsObject.position2 = results[1];
            contentsObject.position3 = results[2];
            contentsObject.position4 = results[3];
            contentsObject.position5 = results[4];
            contentsObject.position6 = results[5];
            contentsObject.position7 = results[6];
            contentsObject.position8 = results[7];
            contentsObject.position9 = results[8];
            contentsObject.position10 = results[9];
            contentsObject.position11 = results[10];
            contentsObject.position12 = results[11];
            contentsObject.position13 = results[12];
            contentsObject.position14 = results[13];
            contentsObject.position15 = results[14];
            
            contentsArray.push(contentsObject);    
        }       
        
        var field = form.addField('results', 'text', 'Number of records loaded');
        field.setDisplayType('inline');
        form.setFieldValues({
            results: contentsArray.length
        });
        
        
        nlapiLogExecution('debug', '--------Start Process-------', null);
        
        
        
        try {
        
            BatchRecords(contentsArray, request.getParameter('batch'));
        } 
        
        catch (e) {
            if (e.getDetails != undefined) {
                nlapiLogExecution('debug', 'Data Loader Error: <br>' + e.getCode() + '<br>' + e.getDetails() + '<br>' + e.getStackTrace());
            }
            else {
                nlapiLogExecution('debug', 'Data Loader Error: <br>' + e.description);
            }
        }
        
        nlapiLogExecution('debug', '--------Process End-------', context.getRemainingUsage());
        
        
        response.writePage(form);
        
        
        
    }
    
    
    
    
}

function BatchRecords(records, batchname){



    nlapiLogExecution('debug', 'Starting Units = ' + context.getRemainingUsage());
    
    
    
    var batch = nlapiCreateRecord(context.getSetting('script', 'custscript_data_loader_record_type'));
    batch.setFieldValue('name', batchname);
    
    
    
    
    for (var i = 0; i < records.length; i++) {
    
    
        batch.insertLineItem('recmachcustrecord_data_loader_batch', i + 1);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos1', i + 1, records[i].position1);
        
        
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos2', i + 1, records[i].position2);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos3', i + 1, records[i].position3);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos4', i + 1, records[i].position4);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos5', i + 1, records[i].position5);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos6', i + 1, records[i].position6);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos7', i + 1, records[i].position7);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos8', i + 1, records[i].position8);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos9', i + 1, records[i].position9);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos10', i + 1, records[i].position10);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos11', i + 1, records[i].position11);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos12', i + 1, records[i].position12);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos13', i + 1, records[i].position13);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos14', i + 1, records[i].position14);
        batch.setLineItemValue('recmachcustrecord_data_loader_batch', 'custrecord_data_loader_pos15', i + 1, records[i].position15);
    }
    
    var batchId = nlapiSubmitRecord(batch);
    
    nlapiLogExecution('debug', 'Ending Units = ' + context.getRemainingUsage());
}


function CSVToArray(strData, strDelimiter){

    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");
    
    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(( // Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
    
    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
    
    // Standard fields.
    "([^\"\\" +
    strDelimiter +
    "\\r\\n]*))"), "gi");
    
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];
    
    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;
    
    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {
    
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];
        
        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (strMatchedDelimiter.length &&
        (strMatchedDelimiter != strDelimiter)) {
        
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);
            
        }
        
        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {
        
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"");
            
        }
        else {
        
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];
            
        }
        
        
        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }
    
    // Return the parsed data.
    return (arrData);
}


var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    
    // public method for encoding
    encode: function(input){
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        
        input = Base64._utf8_encode(input);
        
        while (i < input.length) {
        
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            }
            else 
                if (isNaN(chr3)) {
                    enc4 = 64;
                }
            
            output = output +
            this._keyStr.charAt(enc1) +
            this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) +
            this._keyStr.charAt(enc4);
            
        }
        
        return output;
    },
    
    // public method for decoding
    decode: function(input){
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        
        while (i < input.length) {
        
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            
            output = output + String.fromCharCode(chr1);
            
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
            
        }
        
        output = Base64._utf8_decode(output);
        
        return output;
        
    },
    
    // private method for UTF-8 encoding
    _utf8_encode: function(string){
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        
        for (var n = 0; n < string.length; n++) {
        
            var c = string.charCodeAt(n);
            
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else 
                if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            
        }
        
        return utftext;
    },
    
    // private method for UTF-8 decoding
    _utf8_decode: function(utftext){
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        
        while (i < utftext.length) {
        
            c = utftext.charCodeAt(i);
            
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else 
                if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                }
                else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            
        }
        
        return string;
    }
    
}
